from fastapi import APIRouter, Depends, HTTPException, Request
from app.controllers.category_controller import create_category, add_category
from app.database.db_setup import get_db
from sqlalchemy.orm import Session
import time
from app.utils.response_utils import build_response
from app.utils.request_utils import get_user_params  # 导入全局方法

category_router = APIRouter()


@category_router.post("/create_category/")
@category_router.get("/create_category/")
async def create_category_route(
    request: Request,
    db: Session = Depends(get_db)
):
    # 这里需要 await 来获取实际的值
    params = await get_user_params(request)
    name = params.get("name")
    script_id=params.get("script_id")
    # 打印用户提交的值
    print(f"用户提交的分类名称: {name}")

    if not name:
        return build_response(100, '分类名称不能为空')
    if not script_id:
        return build_response(100, '归属话术不能为空')
    try:
        add_result = add_category(
            category_name=name
        )
        print(f"add_category 方法的返回结果: {add_result}")

        if "error" in add_result:
            return build_response(100, '失败', '名字已存在')

        # 从返回结果中获取 body 部分
        body = add_result.get("body")
        if body is None:
            return build_response(100, '失败', "返回结果有误")

        # 从 body 中获取 Data 部分
        data = body.get("Data")
        if data is None:
            return build_response(100, '失败', "返回结果有误")

        category_id = data.get("CategoryId")
        print(f"获取到的 CategoryId: {category_id}")

        if not category_id:
            return build_response(100, '失败', "返回结果有误")

        # 获取 add_time
        add_time = int(time.time())
        print(f"使用的 add_time: {add_time}")

        # 调用 create_category 方法
        new_category = create_category(
            script_id=script_id,
            name=name,
            CategoryId=category_id,
            add_time=add_time,
            db=db
        )
        print(f"create_category 方法创建的新分类: {new_category}")
        return build_response(200, '成功', new_category)

    except HTTPException as http_exc:
        return build_response(100, '失败', http_exc.detail)
    except Exception as e:
        return build_response(100, '失败', str(e))